<template>
    <div id="order">
        <!--导航栏-->
        <van-nav-bar
                title="填写订单"
                left-text="返回"
                left-arrow
                :fixed=true
                :border=true
                @click-left="onClickLeft"
        />
        <!--收货地址、商品展示-->
<!--        <van-contact-card-->
<!--                :type="address_type"-->
<!--                add-text="选择收货地址"-->
<!--                :name="address_name"-->
<!--                :tel="address_tel"-->
<!--                @click="chooseAddress"-->
<!--                style="margin-top: 3rem"-->
<!--        />-->
          <div style="height:30px;margin-top:45px;background-color:white" v-show="showTime">
              <van-row >
                  <van-col offset:1 span="6" style="margin-left:10px;margin-top:10px;color: red"><span style="font-size:14px">剩余提交时间:</span></van-col>
                  <van-col span="8"><div style="margin-top:14px"><van-count-down millisecond :time="time" format="HH:mm:ss:SS" @finish="finish"/></div></van-col>
              </van-row>
          </div>


        <div id="address-wrap" @click="chooseAddress">
            <div class="name" >
                <span>{{ address.name }} </span>
                <span>{{ address.tel }}</span>
                <span>     邮政编码：{{ address.zipCode }}</span>
            </div>
            <div class="address">
                {{ region }}
            </div>
            <div class="address">
                {{ addressDetail }}
            </div>
            <van-icon class="arrow" name="arrow" />
        </div>
        <van-cell-group style="margin-top: 0.6rem">
<!--            <van-cell title="送达时间" :value="arriveDate" @click="showDatePopup" is-link/>-->
            <router-link :to="{path:'/confirmOrder/orderDetail'}" ref="coupId">
                <van-cell :value="`共${goodsCount}件`" is-link center>
                    <template #title>
                      <!--                         eslint-disable-next-line vue/no-unused-vars,vue/require-v-for-key --->
                        <img v-for="(goods) in threeShopCart" :src=baseURL1+goods.img alt="" style="width: 3rem">
                    </template>
                </van-cell>
            </router-link>
        </van-cell-group>
        <van-cell-group>
            <van-coupon-cell
                    :coupons="coupons"
                    :chosen-coupon="chosenCoupon"
                    @click="showList = true"

            />
            <!-- 优惠券列表 -->
            <van-popup
                    v-model="showList"
                    round
                    position="bottom"
                    style="height: 90%; padding-top: 4px;"

            >
                <van-coupon-list
                        :coupons="coupons"
                        :chosen-coupon="chosenCoupon"
                        :disabled-coupons="disabledCoupons"
                        @change="onChange"
                        @exchange="onExchange"
                        :show-count="isshow"
                        :show-exchange-bar="isshow"
                />
            </van-popup>
        </van-cell-group>
        <!--支付方式-->
        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="支付方式" value="支付宝"/>
        </van-cell-group>
        <!--备注-->
        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="备注" value="微信">
                <label>
                    <input type="text" placeholder="选填，备注您的需求" v-model="notice">
                </label>
            </van-cell>
        </van-cell-group>
        <!--商品金额、配送费-->
        <van-cell-group style="margin-top: 0.6rem">
            <van-cell title="商品金额" :value="'￥'+totalPrice.toFixed(2)"/>
            <van-cell title="邮费" :value="`￥${this.disPrice}`"/>
        </van-cell-group>
        <!--提交订单-->
        <van-submit-bar
                :price="realPrice "
                label="实付"
                button-text="提交订单"
                @submit="onSubmit()"
        />
        <!--弹出日期组件-->
        <van-popup v-model="dateShow" round position="bottom" :style="{height:'30%'}">
            <van-datetime-picker
                    v-model="currentDate"
                    type="datetime"
                    :min-date="minDate"
                    :max-date="maxDate"
                    @cancel="onDateCancel"
                    @confirm="onDateConfirm"
            ></van-datetime-picker>
        </van-popup>
        <!--支付二维码-->
        <van-popup v-model="isPay" round position="center">
            <qriously :value="qrcode" :size="200"/>
        </van-popup>
        <transition name="router-slider" mode="out-in">
            <router-view></router-view>
        </transition>
    </div>

</template>

<script>

import {Toast} from "vant";
import {mapMutations} from "vuex";
import {
    userAddressList,
    getBuyGoods,
    getBuyGoodsNow,
    delcoup,
    getAllCoup,
    getSelectUuid,
    getKill,
    timeOut, getBuyKillGoodsNow
} from "@/api/api";
import Moment from 'moment';
import img from "@/api/api"
    let coupList1 =[];
    let coupList2 =[];


const ads = {
    id: "",
    name: "",
    tel: "",
    address:"",
    zipCode:"",
    isDefault: true,
    addressesId:0,
};
    export default {
      // eslint-disable-next-line vue/multi-word-component-names
        name: "Order",
       created() {

            if(this.$route.query.aid==2){
                this.showTime=true;
            }
           var time = new Date(new Date().getTime());
           var year = time.getFullYear();
           var month = time.getMonth()+1;
           var day = time.getDate();
           var hour = time.getHours();
           var minute = time.getMinutes();
           var second = time.getSeconds();
           this.nowTime=year+'-'+(month<10?'0'+month:month)+'-'+(day<10?'0'+day:day)+' '+(hour<10?'0'+hour:hour)+':'+(minute<10?'0'+minute:minute)+':'+(second<10?'0'+second:second)
           this.nowTime=new Date(Date.parse(this.nowTime));

           getKill().then((response) => {
               if(response.data.code===2000) {
                   this.active = response.data.data.activityList
                   for (let i = 0; i < this.active.length; i++) {
                       if (this.active[i].id == 2) {
                           this.killEndTime = new Date(Date.parse(this.active[i].endTime));
                       }
                   }
               }
           })
           // this.getBussTopDataByTimer();
           coupList1.length=0;
           coupList2.length=0;
           getAllCoup().then((response) => {
               let coup=response.data.data.coupons
             if(coup == undefined || coup.length === 0 ){
               return;
             }
               for (let i = 0; i <coup.length ; i++) {
                   const coupon = {
                       available: "",
                       condition: "",
                       reason: '',
                       value:"",
                       name: "",
                       startAt:"",
                       endAt: "",
                       valueDesc:"",
                       unitDesc: '',
                       id:'',
                   };
                   console.log(coup[i].activeId);
                   if(coup[i].type==2){
                       console.log("111")
                       coupon.condition="满"+coup[i].withAmount+"可用";
                       coupon.value = (10 - (coup[i].usedAmount)*0.1)*this.totalPrice;
                       coupon.valueDesc = (coup[i].usedAmount)*0.1;
                       coupon.unitDesc='折';
                       coupon.name="折扣券";
                       coupon.startAt= new Date(coup[i].startTime).getTime();
                       coupon.endAt=new Date(coup[i].endTime).getTime();
                       coupon.id=coup[i].id;
                       this.coupEndTime=new Date(Date.parse(coup[i].endTime));
                       this.coupStartTime=new Date(Date.parse(coup[i].startTime));

                   }
                   if(coup[i].type==1)
                   {
                       coupon.unitDesc='元';
                       coupon.name="满减券";
                       coupon.condition="满"+coup[i].withAmount+"可用";
                       coupon.value = (coup[i].usedAmount)*100;
                       coupon.valueDesc = (coup[i].usedAmount);
                       coupon.startAt= new Date(coup[i].startTime).getTime();
                       coupon.endAt=new Date(coup[i].endTime).getTime();
                       coupon.id=coup[i].id;

                   }

                   if (coup[i].status==='1'&&this.$route.query.aid!=2&&this.nowTime<this.coupEndTime&&this.nowTime>=this.coupStartTime){
                       coupList1.push(coupon);

                   }else{
                       coupList2.push(coupon);
                           if(coupList2.length!=0){
                       for (let j = 0; j <coupList2.length ; j++) {
                           delcoup(coupList2[i].id).then((response) => {})
                       }
                           }
                   }
               }
           });
           userAddressList().then((response) => {
               console.log(response.data)
               if(response.data.code === 2000){
                   let tempList = response.data.data.address;
                   for(let i = 0; i < tempList.length;i++){
                       if(tempList[i].isDefault==="1"){
                           ads.id = tempList[i].id;
                           this.addressesId= tempList[i].id;
                           ads.name = tempList[i].addName;
                           ads.tel = tempList[i].phone;
                           ads.zipCode = tempList[i].zipCode;
                           ads.address = tempList[i].region+"\n"+tempList[i].detailedAddress;
                           break;
                       }
                   }
                   this.address = this.$store.state.chosenAddress.id === ""?ads:this.$store.state.chosenAddress;

                   if(this.address.address !== undefined){
                       this.region = this.address.address.split("\n")[0];
                       this.addressDetail = this.address.address.split("\n")[1];
                   }
               }else {
                   this.address = ads;
               }

           });
      },
      data() {
            return {
              // config:{
              //       time:"18:20:00",
              //       interval:1,
              //       intervalTimer:'',
              //       timeOutTimer:'',
              //   },

          showTime:false,
                time: 4*60*1000,
                nowTime:"",
                coupEndTime:"",
                coupStartTime:"",
                usedAmount:0,
                withAmount:0,
                couptype:0,
                isshow:false,
                couponId:0,
                showList:false,
                chosenCoupon: -1,
                coupons:coupList1,
                disabledCoupons:coupList2,
                goodsId:[],
                baseURL1:img.src,
                coupId:0,
                dateShow: false,
                minDate: new Date(),
                maxDate: new Date(new Date().getFullYear()+1, new Date().getMonth(), new Date().getDay()),
                currentDate: new Date(),
                // 3. 送达时间
                arriveDate: "请选择送达时间",
                // 4. 备注
                notice: null,
                // 5. 二维码
                isPay: false,
                qrcode: null,
                shopCart: this.$store.state.shopCart,
                address:{},
                region:"",
                addressDetail:"",
                descMoney:0,
                num: 0,
                timer: null,
                uuid:"",
                killEndTime:"",

            }
        },
        destroyed(){
            if(this.timer) { //如果定时器在运行则关闭
                clearInterval(this.timer);
            }
        },

        computed: {

           // 商品总件数
            goodsCount() {
              let goodsCount = 0;
              Object.values(this.shopCart).forEach((goods, index) => {
                  goodsCount+=parseInt(goods.count);
              })
              return goodsCount;
            },
            // 商品总价
            totalPrice() {
                let totalPrice = 0;
                this.shopCart.forEach((t)=>{
                    if(this.$route.query.aid==2&&this.nowTime<this.killEndTime){
                        totalPrice += t.seckillPrice*t.count;
                    }else{
                        totalPrice += t.price*t.count;
                    }

                })
                return totalPrice;
            },
          realPrice(){
            return   (this.totalPrice -  this.descMoney)*100
          },
            // 取购物车前三件选中商品
            threeShopCart() {
                let shopCart = [];
                Object.values(this.shopCart).forEach((goods, index) => {
                        shopCart.push(goods);
                })
                return shopCart.slice(0, 3);
            },
            // 配送费
            disPrice() {
                // 商品总价大于40免配送费  小于40 6元配送费
                return this.totalPrice > 40 && this.totalPrice !== 0 ? 0 : 6;
            }
        },
        methods: {

            finish(){
                Toast('倒计时结束');
                timeOut(this.$route.query.goodid).then((response) =>{
                    if (response.code===2000) {
                        this.$router.push({path:'/goodDetail'})
                    }else {
                        Toast(response.message)
                    }
                        })
            },
            stop() {
                clearInterval(this.timer);
                this.timer = null;
                this.$router.push({path:'/paySuccess',
                query:{
                    status:0
                }
                })
            },
            // 请求是否有新消息
            getProjectList() {
                this.num+=1;
                getSelectUuid(this.uuid).then((response) => {
                       if(response.data.data.code==2000){
                           this.stop()
                       }
                })
                if(this.num==60){
                    this.stop()
                }
            },
            onChange(index) {
                this.showList =  false;
                this.chosenCoupon = index;
                if(index==-1){
                    this.descMoney=0;
                }
                if(coupList1.length>0) {
                  for (let i = 0; i < coupList1.length; i++) {
                    this.couponId = coupList1[index].id;
                    this.couptype = coupList1[index].activeId;
                    this.usedAmount = coupList1[index].usedAmount;
                    this.withAmount = coupList1[index].withAmount;
                    this.descMoney = coupList1[index].value * 0.01;
                  }
                }
                this.$store.commit('updateData',this.couponId)
                   // return totalPrice

            },
            onExchange(code) {
                this.coupons.push(coupList1);
            },

            ...mapMutations(["saveChosenAddress"]),
            onSubmit(){
              let i = 1;
                console.log("111"+this.$route.query.cartNow)
                if(this.address.address === ""){
                  Toast("请添加地址")
                  return
                }



                this.coupId=this.$store.state.coupid
                console.log("kkk"+this.$route.query.cartNow)
                if(this.$route.query.cartNow==1){
                    console.log("mai"+this.$route.query.cartNow)

                    for (let i = 0; i < this.$store.state.shopCart.length; i++) {

                    this.goodsId.push(this.$store.state.shopCart[i].id)
                        console.log(this.goodsId.length);
                }
                    if(this.$route.query.cartNow==1){
                getBuyGoods(this.goodsId,this.addressesId,this.coupId).then((response) => {
                    // this.goodsInfo=response.data.data.goodList;
                    if (response.data.code===2000) {
                            let uuid = response.data.data.uuid;
                            this.uuid=uuid;
                            let price = this.realPrice * 0.01;
                            //账号:esnyth2931@sandbox.com
                            //密码:111111
                            //支付密码:111111
                            window.open("http://112.74.38.95:7000/check/pay-serv/alipay/pay?subject=" + uuid + "&traceNo=" + uuid + "&totalAmount=" + price)
                    console.log("走到这里")
                        this.timer = window.setInterval(() => {
                            setTimeout(this.getProjectList(), 0);
                        }, 5000);
                        console.log(this.coupId)
                        if(this.coupId===null||this.coupId===""||this.coupId===undefined){
                        }else{
                            delcoup(this.coupId).then((response) => {})
                        }
                    }else {
                      Toast(response.data.message);
                    }
                    // this.$router.push({path:'/paySuccess'})
                });
                    // this.isPay = false;
                    //     this.$router.replace('/dashboard/mine');
                }
                }else if(this.$route.query.aid==1||this.$route.query.aid==0){
                    console.log("uuu"+this.$route.query.goodsTwoId + this.realPrice)
                    getBuyGoodsNow(this.$route.query.goodsTwoId,this.addressesId,this.coupId).then((response) => {
                        if (response.data.code===2000) {
                            let uuid = response.data.data.uuid;
                            this.uuid=uuid;
                            let price = this.realPrice * 0.01;

                            //账号:esnyth2931@sandbox.com
                            //密码:111111
                            //支付密码:111111

                            window.open("http://112.74.38.95:7000/check/pay-serv/alipay/pay?subject=" + uuid + "&traceNo=" + uuid + "&totalAmount=" + price)
                            // this.$router.push({path:'/paySuccess'}
                            this.timer = window.setInterval(() => {
                                setTimeout(this.getProjectList(), 0);
                            }, 5000);
                            if(this.coupId===null||this.coupId===""||this.coupId===undefined){
                            }else{
                                delcoup(this.coupId).then((response) => {})
                            }
                        }else {
                            Toast(response.data.message);
                        }
                        // this.$router.push({path:'/paySuccess'})
                    });
                    // delcoup(1, this.coupId).then((response) => {})
                }

                else if(this.$route.query.aid==2){

                  console.log("uuu"+this.$route.query.goodsTwoId + this.realPrice)
                    getBuyKillGoodsNow(this.$route.query.goodsTwoId,this.addressesId,this.coupId).then((response) => {
                    if (response.data.code===2000) {
                      let uuid = response.data.data.uuid;
                        this.uuid=uuid;
                      let price = this.realPrice * 0.01;

                      //账号:esnyth2931@sandbox.com
                      //密码:111111
                      //支付密码:111111

                      window.open("http://112.74.38.95:7000/check/pay-serv/alipay/pay?subject=" + uuid + "&traceNo=" + uuid + "&totalAmount=" + price)
                      // this.$router.push({path:'/paySuccess'}
                        this.timer = window.setInterval(() => {
                            setTimeout(this.getProjectList(), 0);
                        }, 5000);
                           if(this.coupId===null||this.coupId===""||this.coupId===undefined){
                           }else{
                               delcoup(this.coupId).then((response) => {})
                           }
                    }else {
                      Toast(response.data.message);
                    }
                      // this.$router.push({path:'/paySuccess'})
                  });
                    // delcoup(1, this.coupId).then((response) => {})
                }
            // this.coupId=this.$store.state.coupid
                    //
                    // getBuyGoods(1,this.$route.query.goodsTwoId,this.addressesId,this.coupId).then((response) => {
                    //     // this.goodsInfo=response.data.data.goodList;
                    // });




            },
            onClickLeft() { // 点击左边
                this.$router.back();  // 返回上一个路由
            },
            chooseAddress() {
                this.$router.push('/confirmOrder/myAddress');
            },
            // 展示日期组件
            showDatePopup() {
                this.dateShow = true;
            },
            // 取消日期组件
            onDateCancel() {
                this.dateShow = false;
            },
            // 确认日期组件
            onDateConfirm(value) {
                this.dateShow = false;
                this.arriveDate = Moment(value).format('YYYY-MM-DD hh:mm');
            },
//             getBussTopDataByTimer() {
//
// //获取下次要执行的时间，如果执行时间已经过了今天，就让把执行时间设到明天的按时执行的时
//                 var nowTime = new Date().getTime();
//                 var timePoint = this.config.time.split( ' : ' ).map((i) => parseInt(i));
//                 var recent = new Date().setHours(...timePoint);//获取执行时间的时间戳
//                 if (recent <= nowTime){
//                     recent += 24 * 60* 6*100}
//                 //未来程序执行的时间减去现在的时间，就是程序要多少秒之后执行
//                 var doRunTime = recent - nowTime
//                 this.config.timeOutTimer = setTimeout(this.setTimer,doRunTime)
//             },
//             setTimer() {
//                  console.log( '进入定时器')
//                 //配置后的第一天12点执行
//                  this.initTopTenBusiness()
//                 //每隔多少天再执行一次
//                     var intTime = this.config.interval * 24*60*60*1000
//                     this.config.intervalTimer = setInterval(this.initTopTenBusiness,intTime)
//             },
//             initTopTenBusiness(){
//                 console.log( '执行定时器')
//             }
},
      watch:{
          '$store.state.chosenAddress':function(){ //监听vuex中chosenAddress变化而改变address里面的值
              this.address=this.$store.state.chosenAddress;
              this.addressesId=this.$store.state.chosenAddress.id;
        }
      },
    }
</script>

<style scoped>
   /deep/  .address-wrap[data-v-de889afa] {
       margin-bottom: 20px;
       background: #fff;
       position: relative;
       margin-top: 0px;
       font-size: 14px;
       padding: 15px;
       color: #222333;
   }
    #order {
        width: 100%;
        height: 100%;
        background-color: #f5f5f5;
    }

    .router-slider-enter-active, .router-slider-leave-active {
        transition: all 0.3s;
    }

    .router-slider-enter, .router-slider-leave-active {
        transform: translate3d(2rem, 0, 0);
        opacity: 0;
    }

    input {
        text-align: right;
    }

    ::-webkit-input-placeholder { /* WebKit browsers */
        direction: rtl;
    }

    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
        direction: rtl;
    }

    ::-moz-placeholder { /* Mozilla Firefox 19+ but I'm not sure about working */
        direction: rtl;
    }

    :-ms-input-placeholder { /* Internet Explorer 10+ */
        direction: rtl;
    }
   #address-wrap {
       margin-bottom: 20px;
       background: #fff;
       position: relative;
       margin-top: 44px;
       font-size: 14px;
       padding: 15px;
       color: #222333;
   }
   .address-wrap  .name, .address {
       margin: 10px 0;
   }
    .arrow {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
    }
    .address-wrap::before {
       position: absolute;
       right: 0;
       bottom: 0;
       left: 0;
       height: 2px;
       background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
       background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
       background-size: 80px;
       content: '';
     }
</style>
